<?php
class User_Admin extends User{
    
    protected static $_instance = NULL;
    protected $_permissions = null;
    /**
     * @return User_Admin
     */
	static public function getInstance(){
        if(is_null(self::$_instance))
           self::$_instance = new self();
        return self::$_instance;   
    }	
    
    protected function __construct(){
        parent::__construct();
    }  
    /**
     * Get modules wich user can view
     * @return array
     */
    public function getAvailableModules(){   
        if(is_null($this->_permissions))
            $this->_loadPermissions();
        
        $data = array(); 
        if(!empty($this->_permissions))
            foreach ($this->_permissions as $name=>$config)
                if($config['view'])
                    $data[$name] = $name;
                
        return $data;
    } 
    /**
     * Load user permissions
     * @return void
     */
    protected function _loadPermissions(){
        $this->_permissions = Model_Permissions::getInstance()->getPermissions($this->_id , $this->group_id);
    }
    /**
     * (non-PHPdoc)
     * @see User::setId()
     */
    public function setId($id){
        parent::setId($id);
        $this->_permissions = null;
    }   
    /**
     * Check if user can view module data
     * @param string $module
     * @return boolean
     */
    public function canView($module){
       return $this->_checkPermission($module, 'view'); 
    }
    /**
     * Check if user can edit module data
     * @param string $module
     * @return boolean
     */
    public function canEdit($module){
        return $this->_checkPermission($module, 'edit');  
    }
    /**
     * Check if user can delete module data
     * @param string $module
     * @return boolean
     */
    public function canDelete($module){
        return $this->_checkPermission($module, 'delete'); 
    }
    /**
     * Check if user can publish module data
     * @param string $module
     * @return boolean
     */
    public function canPublish($module){
        return $this->_checkPermission($module, 'publish'); 
    }
    /**
     * Check permission for module
     * @param string $module - module name
     * @param string $perm  - permission type
     * @return boolean
     */
    protected function _checkPermission($module , $perm){
        if(is_null($this->_permissions))
           $this->_loadPermissions();

        if(isset($this->_permissions[$module]) && $this->_permissions[$module][$perm])
            return true;
        else 
            return false;  
    }
    /**
     * (non-PHPdoc)
     * @see User::_checkAuthSession()
     */
    protected function _checkAuthSession(){
         $ses = Store::factory(Store::Session);
         if($ses->keyExists('admin') && $ses->get('admin'))
             parent::_checkAuthSession();
    }
}